package cn.com.xf.web.controller;

import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.xf.common.AbstractBaseController;
import cn.com.xf.common.Constants;
import cn.com.xf.common.StringUtil;
import cn.com.xf.domain.TblOaDuty;
import cn.com.xf.domain.TblOaDutySchedule;
import cn.com.xf.domain.TsDict;
import cn.com.xf.domain.TsSiteinfo;
import cn.com.xf.service.CompanyService;
import cn.com.xf.service.DutyService;
import cn.com.xf.utils.DateUtils;
import cn.com.xf.utils.encode.EncrypTool;
import cn.com.xf.web.PageModel;
import cn.com.xf.web.form.DutyForm;
import cn.com.xf.web.security.UserInfo;

//需要修改发布
/**
 * @author yyp 值班信息controller
 */
@Controller
@RequestMapping("/duty")
public class DutyController extends AbstractBaseController {

	@Autowired
	private DutyService dutyService;
	@Autowired
	private CompanyService companyService;
	
	@RequestMapping(value = "/step")
	public ModelAndView duty_step(HttpServletRequest request, HttpServletResponse response) throws Exception {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		DutyForm form = new DutyForm();
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		Date date = cal.getTime();
		String dutyDate = DateUtils.formatDate(date);
		// 查询参数封装
		form.setDutyDate(dutyDate);
		form.setSiteId(userInfo.getSiteId());
		form.setDeptId(userInfo.getDeptId());
		form.setSiteName(userInfo.getSiteName());
		// 设置默认站点
		if (userInfo.getSiteId().equals("")) {
			form.setSiteId(getDefaultSiteId());
		}
		if(form.getSiteId()==null||form.getSiteId().equals("")){
			String empId = userInfo.getUsername();
			String checkId = dutyService.selectSiteIdByUser(empId);
			form.setSiteId(checkId);
		}
		if(form.getSiteId()==null||form.getSiteId().equals("")){
			form.setSiteId("769000");
		}
		if (form.getDeptId() == null || form.getDeptId().equals("")) {
			String name = userInfo.getUsername();
			String deptId = dutyService.selectDeptIdByUser(name);
			if(deptId==null||deptId.length()<=0){
				deptId = "D999";
			}
			form.setDeptId(deptId);
		}
		ModelAndView mv = new ModelAndView("/notice/duty", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}

	@RequestMapping(value = "/list")
	public ModelAndView notice_list(HttpServletRequest request, HttpServletResponse response, DutyForm form)
			throws Exception {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		ModelAndView mv = new ModelAndView("/notice/duty_list", Constants.FORM_COMMAND_KEY, form);
		// 1.模糊搜索关键字
		String isAll = "no";
		String siteId = StringUtil.StringFilter(form.getSiteId());
		String userId = StringUtil.StringFilter(form.getUserId());
		String deptId = StringUtil.StringFilter(form.getDeptId());
		String date = StringUtil.StringFilter(form.getDutyDate());
		Date dutyDate = getMondayDate(date);
		// 设置默认站点
		if (siteId.equals("")) {
			siteId = getDefaultSiteId();
		}
		if (siteId == null||siteId.equals("")) {
			String empId = userInfo.getUsername();
			String checkId = dutyService.selectSiteIdByUser(empId);
			siteId = checkId;
		}
		if(siteId==null||siteId.equals("")){
			siteId = "769000";
		}
		form.setSiteId(siteId);
		form.setUserId(userId);
		form.setDeptId(deptId);
		form.setDutyDate(DateUtils.formatDate(dutyDate));
		//查询所有部门
		if(deptId.equals("")||deptId==null||deptId.equals("D999")){
			Map<String, Map<String,List<ArrayList<TblOaDuty>>>> map = new HashMap<String, Map<String,List<ArrayList<TblOaDuty>>>>();
			List<TsDict> deptList = companyService.selectDepts();
			TblOaDuty tblOaDuty = new TblOaDuty();
			tblOaDuty.setSiteId(siteId);
			tblOaDuty.setDutyDate(dutyDate);
			for(int i=0;i<deptList.size();i++){
				tblOaDuty.setDeptId(deptList.get(i).getDictid());
				List<TblOaDuty> list = dutyService.selectDutys(tblOaDuty);
				if (list.size() > 0) {
					//封装数据到班次列表
					Map<String, List<ArrayList<TblOaDuty>>> scheduleMap = handleDutyData(list,dutyDate);
					map.put(deptList.get(i).getDictname(), scheduleMap);
				}
			}
			isAll = "yes";
			mv.addObject("dutyMap",map);
			mv.addObject("isAll",isAll);
			return mv;
		}
		
		TblOaDuty tblOaDuty = new TblOaDuty();
		tblOaDuty.setSiteId(siteId);
		tblOaDuty.setDeptId(deptId);
		tblOaDuty.setDutyDate(dutyDate);

		List<TblOaDuty> list = dutyService.selectDutys(tblOaDuty);
		//封装数据到班次列表
		Map<String, List<ArrayList<TblOaDuty>>> scheduleMap = handleDutyData(list,dutyDate);
		if (list.size() > 0) {
			form.setDeptName(list.get(0).getDeptName());
		} else {
			form.setDeptName("无内容");
		}
		mv.addObject("dutyMap",scheduleMap);
		mv.addObject("isAll",isAll);
		return mv;
	}

	@RequestMapping(value = "/manage")
	public ModelAndView duty_manage(HttpServletRequest request, HttpServletResponse response, DutyForm form)
			throws Exception {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		ModelAndView mv = new ModelAndView("/notice/duty_list_manage", Constants.FORM_COMMAND_KEY, form);
		String siteId = StringUtil.StringFilter(form.getSiteId());
		String deptId = StringUtil.StringFilter(form.getDeptId());
		String date = StringUtil.StringFilter(form.getDutyDate());
		// 时间处理
		Date dutyDate = getMondayDate(DateUtils.formatDate(new Date()));
		if (siteId.equals("")|| siteId == null) {
			siteId = userInfo.getSiteId();
		}
		// 设置默认站点
		if (siteId == null||siteId.equals("")) {
			String empId = userInfo.getUsername();
			String checkId = dutyService.selectSiteIdByUser(empId);
			siteId = checkId;
		}
		// 设置默认时间
		if (!date.equals("") && date != null) {
			dutyDate = getMondayDate(date);
		}
		//设置默认部门
		if (deptId == null || deptId.equals("")||deptId.equals("D999")) {
			String name = userInfo.getUsername();
			deptId = dutyService.selectDeptIdByUser(name);
			if(deptId==null||deptId.length()<=0){
				deptId = "D999";
			}
		}
		form.setSiteId(siteId);
		form.setDeptId(deptId);
		form.setDutyDate(DateUtils.formatDate(dutyDate));
		form.setSiteName(userInfo.getSiteName());
		
		int count = 0;
		if(siteId!=null&&deptId!=null){
			count = dutyService.selectDutyCount(siteId, deptId, dutyDate);
		if (count == 0)
			return mv;

		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();
		List<TblOaDuty> list = dutyService.selectDutys(begin, pageSize, siteId, deptId, dutyDate);
		mv.addObject("list", list);
		}else {
			mv.addObject("list", new ArrayList<TblOaDuty>());
		}
		return mv;
	}
	
	@RequestMapping(value = "/copySearch")
	@ResponseBody
	public List<TblOaDuty> copy_duty_search(HttpServletRequest request, HttpServletResponse response, DutyForm form)
			throws Exception {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = StringUtil.StringFilter(form.getSiteId());
		String deptId = StringUtil.StringFilter(form.getDeptId());
		String date = StringUtil.StringFilter(form.getDutyDate());
		// 时间处理
		Date dutyDate = getMondayDate(DateUtils.formatDate(new Date()));
		if (siteId.equals("")|| siteId == null) {
			siteId = userInfo.getSiteId();
		}
		if (deptId.equals("") ||deptId == null) {
			deptId = userInfo.getDeptId();
		}
		// 设置默认站点
		if (siteId == null||siteId.equals("")) {
			siteId = getDefaultSiteId();
		}
		if (siteId == null||siteId.equals("")) {
			String empId = userInfo.getUsername();
			String checkId = dutyService.selectSiteIdByUser(empId);
			siteId = checkId;
		}
		//设置默认部门
		if (deptId == null || deptId.equals("")||deptId.equals("D999")) {
			String name = userInfo.getUsername();
			deptId = dutyService.selectDeptIdByUser(name);
			if(deptId==null||deptId.length()<=0){
				deptId = "D999";
			}
		}
		// 设置默认时间
		if (!date.equals("") && date != null) {
			dutyDate = getMondayDate(date);
		}
		form.setSiteId(siteId);
		form.setDeptId(deptId);
		form.setDutyDate(DateUtils.formatDate(dutyDate));

		TblOaDuty tblOaDuty = new TblOaDuty();
		tblOaDuty.setSiteId(siteId);
		tblOaDuty.setDeptId(deptId);
		tblOaDuty.setDutyDate(dutyDate);

		List<TblOaDuty> list = dutyService.copyDutys(tblOaDuty);
		if (list.size() > 0) {
			for(int i=0;i<list.size();i++){
				list.get(i).setDutyDateStr(DateUtils.formatDate(list.get(i).getDutyDate()));
			}
			form.setDeptName(list.get(0).getDeptName());
		} else {
			form.setDeptName("无内容");
		}
		return list;
	}
	
	@RequestMapping(value = "/manageSchedules")
	public ModelAndView manageSchedule(HttpServletRequest request, HttpServletResponse response, DutyForm form)
			throws Exception {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		ModelAndView mv = new ModelAndView("/notice/schedule_list_manage", Constants.FORM_COMMAND_KEY, form);
		String siteId = StringUtil.StringFilter(form.getSiteId());
		String deptId = StringUtil.StringFilter(form.getDeptId());
		if (siteId.equals("")|| siteId == null) {
			siteId = userInfo.getSiteId();
		}
		if (deptId.equals("") ||deptId == null) {
			deptId = userInfo.getDeptId();
		}
		// 设置默认站点
		if (siteId == null||siteId.equals("")) {
			siteId = getDefaultSiteId();
		}
		if (siteId == null||siteId.equals("")) {
			String empId = userInfo.getUsername();
			String checkId = dutyService.selectSiteIdByUser(empId);
			siteId = checkId;
		}
		//设置默认部门
		if (deptId == null || deptId.equals("")||deptId.equals("D999")) {
			String name = userInfo.getUsername();
			deptId = dutyService.selectDeptIdByUser(name);
			if(deptId==null||deptId.length()<=0){
				deptId = "D999";
			}
		}
		form.setSiteId(siteId);
		form.setDeptId(deptId);
		if(siteId!=null&&deptId!=null){
			List<TblOaDutySchedule> list = dutyService.selectSchedules(siteId, deptId);
			mv.addObject("list", list);
		}else {
			mv.addObject("list", new ArrayList<TblOaDutySchedule>());
		}
		return mv;
	}
	
	@RequestMapping("/editDuty")
	public ModelAndView editDuty(HttpServletRequest request, HttpServletResponse response, DutyForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/notice/edit_duty", Constants.FORM_COMMAND_KEY, form);
		String id = form.getDutyId();
		TblOaDuty duty = dutyService.selectDutyById(id);
		mv.addObject("duty", duty);
		return mv;
	}
	
	//修改部门班次信息
	@RequestMapping("/editSchedule")
	public ModelAndView editSchedule(HttpServletRequest request, HttpServletResponse response, DutyForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/notice/edit_schedule", Constants.FORM_COMMAND_KEY, form);
		String id = form.getScheduleId();
		TblOaDutySchedule schedule = dutyService.selectScheduleById(id);
		mv.addObject("schedule", schedule);
		return mv;
	}
	
	//增加部门班次信息
	@RequestMapping("/addSchedule")
	public ModelAndView addSchedule(HttpServletRequest request, HttpServletResponse response, DutyForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/notice/add_schedule", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}

	/**
	 * 修改值班表
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/doEditDuty")
	public ModelAndView doEditDuty(HttpServletRequest request, HttpServletResponse response, DutyForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/notice/add_duty_result", Constants.FORM_COMMAND_KEY, form);
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String moifyUserId = form.getMoifyUserId();
		if(moifyUserId==null||moifyUserId.equals("")){
			moifyUserId = userInfo.getUsername();
		}
		String idStr = form.getDutyId();
		String realId = "";
		if (StringUtils.isNotBlank(idStr)) {
			realId = EncrypTool.dencode(idStr);
		}
		//获取数据
		form.setSiteId(form.getEditSiteId());
		form.setDeptId(form.getEditDeptId());
		form.setMoifyUserId(moifyUserId);
		String userTelNo = form.getUserTelNo();
		String userId = form.getUserId();
		TblOaDuty duty = dutyService.selectDutyById(realId);
		if (duty != null) {
			Map<String, String> errMap = dutyService.updateDuty(form, realId);
			if (!CollectionUtils.isEmpty(errMap)) {
				mv.addObject("msg", errMap.get("errMsg"));
				return mv;
			}
			int result = dutyService.updateUserTelNo(userId,userTelNo);
			if (result > 0) {
			mv.addObject("status", "SUCCESS");
			}
		}
		return mv;
	}
	//修改班次信息
	@RequestMapping("/doEditSchedule")
	public ModelAndView doEditSchedule(HttpServletRequest request, HttpServletResponse response, DutyForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/notice/add_schedule_result", Constants.FORM_COMMAND_KEY, form);
		String idStr = form.getScheduleId();
		String realId = "";
		if (StringUtils.isNotBlank(idStr)) {
			realId = EncrypTool.dencode(idStr);
		}
		String siteId = form.getSiteId();
		String deptId = form.getDeptId();
		String deptTelNo = form.getDeptTelNo();
		TblOaDutySchedule duty = dutyService.selectScheduleById(realId);
		if (duty != null) {
			int count = dutyService.updateSchedule(form, realId);
			int result = dutyService.updateDeptTelNo(siteId,deptId,deptTelNo);
			if (count > 0&&result > 0) {
				mv.addObject("status", "SUCCESS");
			}
		}
		return mv;
	}
	/**
	 * 增加值班班次
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/doAddSchedule")
	public ModelAndView doAddSchedule(HttpServletRequest request, HttpServletResponse response,
		DutyForm form) throws Exception {
		ModelAndView mv = new ModelAndView("/notice/add_schedule_result", Constants.FORM_COMMAND_KEY, form);
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Map<String, String> errMap = new HashMap<String, String>();
		String errMsg = "";
		//1.获取数据
		String siteId = form.getSiteId();
		String deptId = form.getDeptId();
		String className = form.getScheduleName();
		String startTime = form.getStartTime();
		String endTime = form.getEndTime();
		String deptTelNo = form.getDeptTelNo();
		// 设置默认站点
		String enterSiteId = userInfo.getSiteId();
		if (userInfo.getSiteId().equals("")|| userInfo.getSiteId() == null) {
			enterSiteId = getDefaultSiteId();
		}
		if (enterSiteId == null||enterSiteId.equals("")) {
			String empId = userInfo.getUsername();
			String checkId = dutyService.selectSiteIdByUser(empId);
			enterSiteId = checkId;
		}
		//验证表单数据
		if (StringUtils.isBlank(className)) {
			errMsg = "班次名称未设置";
			errMap.put("errMsg", errMsg);
			mv.addObject("msg", errMap.get("errMsg"));
			return mv;
		}
		if (StringUtils.isBlank(startTime)) {
			errMsg = "开始时间未设置";
			errMap.put("errMsg", errMsg);
			mv.addObject("msg", errMap.get("errMsg"));
			return mv;
		}
		if (StringUtils.isBlank(endTime)) {
			errMsg = "结束时间未设置";
			errMap.put("errMsg", errMsg);
			mv.addObject("msg", errMap.get("errMsg"));
			return mv;
		}
		if (StringUtils.isBlank(deptTelNo)) {
			errMsg = "部门电话未设置";
			errMap.put("errMsg", errMsg);
			mv.addObject("msg", errMap.get("errMsg"));
			return mv;
		}
		//2.封装数据
		TblOaDutySchedule schedule = new TblOaDutySchedule();
		schedule.setSiteId(siteId);
		schedule.setDeptId(deptId);
		schedule.setClassName(className);
		schedule.setStartTime(startTime);
		schedule.setEndTime(endTime);
		schedule.setTelNo(deptTelNo);
		schedule.setEnterUserId(userInfo.getUsername());
		schedule.setEnterSiteId(enterSiteId);
		schedule.setEnterTime(new Date());
		
		int count = dutyService.insertSchedule(schedule);
		int count2 = dutyService.updateDeptTelNo(siteId,deptId,deptTelNo);
		if(count>0&&count2>0){
			mv.addObject("status", "SUCCESS");
		}
		return mv;
	}
	
	/**
	 * 删除值班信息
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deleteDuty")
	@ResponseBody
	public Map<String, Object> deleteDuty(HttpServletRequest request, HttpServletResponse response, DutyForm form)
			throws Exception {
		String idStr = form.getDutyId();
		int result = dutyService.deleteDuty(idStr);
		Map<String, Object> map = new HashMap<String, Object>();
		if (result > 0) {
			map.put("status", "SUCCESS");
		} else {
			map.put("status", "FAILD");
		}
		return map;
	}
	@RequestMapping("/deleteSchedule")
	@ResponseBody
	public Map<String, Object> deleteSchedule(HttpServletRequest request, HttpServletResponse response, DutyForm form)
			throws Exception {
		String idStr = form.getScheduleId();
		int result = dutyService.deleteSchedule(idStr);
		Map<String, Object> map = new HashMap<String, Object>();
		if (result > 0) {
			map.put("status", "FAILD");
		} else {
			map.put("status", "SUCCESS");
		}
		return map;
	}
			
			
			
	/**
	 * 添加值班信息
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @param result
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/doAddDuty")
	@ResponseBody
	public Map<String, Object> doAddDuty(HttpServletRequest request, HttpServletResponse response,
			@Valid DutyForm form, BindingResult result) throws Exception {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Map<String, Object> map = new HashMap<String, Object>();
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			map.put("errorJson", errorJson);
			return map;
		}
		// 设置默认站点
		String enterSiteId = userInfo.getSiteId();
		if (userInfo.getSiteId().equals("") || userInfo.getSiteId() == null) {
			enterSiteId = getDefaultSiteId();
		}
		if (enterSiteId == null||enterSiteId.equals("")) {
			String empId = userInfo.getUsername();
			String checkId = dutyService.selectSiteIdByUser(empId);
			enterSiteId = checkId;
		}
		String dutyJson = form.getDutyJson();
		JSONParser jp = new JSONParser();
		JSONArray formJson = (JSONArray) jp.parse(dutyJson);
		List<TblOaDuty> dutyList = new ArrayList<TblOaDuty>();
		for (int i = 0; i < formJson.size(); i++) {
			JSONObject jons = (JSONObject) formJson.get(i);
			TblOaDuty duty = new TblOaDuty();
			/*int rowIndex = i + 1;
			if (!isSiteId(jons.get("siteId") + "")) {
				map.put("status", "FAILD");
				map.put("msg", "第&nbsp<font color='#FF0000'>" + rowIndex + "</font>&nbsp条记录所属公司不合法，请校对后单独添加！");
				return map;
			}*/
			duty.setSiteId(form.getEditSiteId());
			duty.setDeptId(form.getEditDeptId());
			duty.setUserId(jons.get("userId") + "");
			duty.setDutyDate(DateUtils.parseDate(jons.get("dutyDateStr") + ""));
			duty.setScheduleId(jons.get("scheduleId") + "");
			duty.setUserTelNo(jons.get("userTelNo") + "");
			duty.setEnterUserId(userInfo.getUsername());
			duty.setEnterSiteId(enterSiteId);
			duty.setEnterTime(new Date());
			dutyList.add(duty);
		}
		for (TblOaDuty duty : dutyList) {
			// 添加
			if (!duty.getUserId().contains(",")) {
				dutyService.insertDuty(duty);
				dutyService.updateUserTelNo(duty.getUserId(),duty.getUserTelNo());
			} else {
				String[] userids = duty.getUserId().split(",");
				for (String userid : userids) {
					duty.setUserId(userid);
					dutyService.insertDuty(duty);
					dutyService.updateUserTelNo(duty.getUserId(),duty.getUserTelNo());
				}
			}
		}
		map.put("status", "SUCCESS");
		return map;
	}

	/**
	 * 复制值班信息
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @param result
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/doCopyDuty")
	@ResponseBody
	public Map<String, Object> doCopyDuty(HttpServletRequest request, HttpServletResponse response,
			@Valid DutyForm form, BindingResult result) throws Exception {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Map<String, Object> map = new HashMap<String, Object>();
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			map.put("errorJson", errorJson);
			return map;
		}
		// 设置默认站点
		String enterSiteId = userInfo.getSiteId();
		if (userInfo.getSiteId().equals("") || userInfo.getSiteId() == null) {
			enterSiteId = getDefaultSiteId();
		}
		if (enterSiteId == null||enterSiteId.equals("")) {
			String empId = userInfo.getUsername();
			String checkId = dutyService.selectSiteIdByUser(empId);
			enterSiteId = checkId;
		}
		String dutyJson = form.getDutyJson();
		JSONParser jp = new JSONParser();
		JSONArray formJson = (JSONArray) jp.parse(dutyJson);
		List<TblOaDuty> dutyList = new ArrayList<TblOaDuty>();
		for (int i = 0; i < formJson.size(); i++) {
			JSONObject jons = (JSONObject) formJson.get(i);
			TblOaDuty duty = new TblOaDuty();
			/*int rowIndex = i + 1;
			if (!isSiteId(jons.get("siteId") + "")) {
				map.put("status", "FAILD");
				map.put("msg", "第&nbsp<font color='#FF0000'>" + rowIndex + "</font>&nbsp条记录所属公司不合法，请校对后单独添加！");
				return map;
			}*/
			duty.setSiteId(form.getEditSiteId());
			duty.setDeptId(form.getEditDeptId());
			duty.setUserId(jons.get("userId") + "");
			duty.setDutyDate(DateUtils.parseDate(jons.get("dutyDateStr") + ""));
			duty.setScheduleId(jons.get("scheduleId") + "");
			duty.setUserTelNo(jons.get("userTelNo") + "");
			duty.setEnterUserId(userInfo.getUsername());
			duty.setEnterSiteId(enterSiteId);
			duty.setEnterTime(new Date());
			dutyList.add(duty);
		}
		for (TblOaDuty duty : dutyList) {
			// 添加
			if (!duty.getUserId().contains(",")) {
				dutyService.insertDuty(duty);
				dutyService.updateUserTelNo(duty.getUserId(),duty.getUserTelNo());
			} else {
				String[] userids = duty.getUserId().split(",");
				for (String userid : userids) {
					duty.setUserId(userid);
					dutyService.insertDuty(duty);
					dutyService.updateUserTelNo(duty.getUserId(),duty.getUserTelNo());
				}
			}
		}
		map.put("status", "SUCCESS");
		return map;
	}
	
	
	@RequestMapping(value = "/addDutys")
	public ModelAndView add_dutys(HttpServletRequest request, HttpServletResponse response,DutyForm form) throws Exception {
		return new ModelAndView("/notice/add_duty", Constants.FORM_COMMAND_KEY, form);
	}

	@RequestMapping(value = "/stepCopy")
	public ModelAndView stepCopy(HttpServletRequest request, HttpServletResponse response,DutyForm form) throws Exception {
		if(form.getDutyDate()==null||form.getDutyDate().equals("")){
			form.setDutyDate(DateUtils.formatDate(new Date()));
		}
		return new ModelAndView("/notice/copy_duty", Constants.FORM_COMMAND_KEY, form);
	}
	
	@RequestMapping("/exportDuty")
	public void exportDuty(HttpServletRequest request, HttpServletResponse response, DutyForm form) throws Exception {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		
		//获取参数
		String siteId = StringUtil.StringFilter(form.getSiteId());
		String deptId = StringUtil.StringFilter(form.getDeptId());
		String date = StringUtil.StringFilter(form.getDutyDate());
		Date dutyDate = getMondayDate(date);
		// 设置默认站点
		if (siteId.equals("")) {
			siteId = getDefaultSiteId();
		}
		if (siteId == null||siteId.equals("")) {
			String empId = userInfo.getUsername();
			String checkId = dutyService.selectSiteIdByUser(empId);
			siteId = checkId;
		}
		
		//查询所有部门
		if(deptId.equals("")||deptId==null||deptId.equals("D999")){
			Map<String, Map<String,List<ArrayList<TblOaDuty>>>> map = new HashMap<String, Map<String,List<ArrayList<TblOaDuty>>>>();
			List<TsDict> deptList = companyService.selectDepts();
			TblOaDuty tblOaDuty = new TblOaDuty();
			tblOaDuty.setSiteId(siteId);
			tblOaDuty.setDutyDate(dutyDate);
			for(int i=0;i<deptList.size();i++){
				tblOaDuty.setDeptId(deptList.get(i).getDictid());
				List<TblOaDuty> list = dutyService.selectDutys(tblOaDuty);
				if (list.size() < 0) {
					System.out.println("导出值班表内容为空，已取消下载！！！！！！！！！！");
					return;
				}
				if (list.size() > 0) {
					//封装数据到班次列表
					Map<String, List<ArrayList<TblOaDuty>>> scheduleMap = handleDutyData(list,dutyDate);
					map.put(deptList.get(i).getDictname(), scheduleMap);
				}
			}
			
			// 生成表名
			String expSiteName = userInfo.getSiteName();
			String sheetName = expSiteName + "所有部门" + DateUtils.formatDate(dutyDate) + "值班表";

			// 生成日期列名
			SimpleDateFormat formater2 = new SimpleDateFormat("MM/dd");
			String[] strs = new String[7];
			Calendar cal = Calendar.getInstance();
			cal.setTime(dutyDate);
			for (int i = 0; i < 7; i++) {
				String weekDay = getWeekDay(cal.getTime());
				strs[i] = formater2.format(cal.getTime()) + weekDay;
				cal.add(Calendar.DATE, 1);
			}
			//所有列名
			String[] title = { "所属公司", "部门", "班次", strs[0], strs[1], strs[2], strs[3], strs[4], strs[5], strs[6] };
			// 1.创建一个workbook，对应一个Excel文件
			HSSFWorkbook wb = new HSSFWorkbook();
			// 2.在workbook中添加一个sheet，对应Excel中的一个sheet
			HSSFSheet sheet = wb.createSheet(sheetName);
			for(int i=0;i<10;i++){
				sheet.setColumnWidth(i,8*2*256);
			}
			// 3.在sheet中添加表头第0行，老版本poi对excel行数列数有限制short
			sheet.createFreezePane(0, 1, 0, 1);
			HSSFRow row = sheet.createRow((int) 0);
			// 4.创建单元格，设置值表头，设置表头居中
			HSSFCellStyle style = wb.createCellStyle();
			// 居中格式
			style.setWrapText(true);
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中 
			HSSFCell cell = null;
			for (int i = 0; i < title.length; i++) {
				cell = row.createCell(i);
				cell.setCellValue(title[i]);
				cell.setCellStyle(style);
			}
			
			//5.输出所有部门
				Set<String> deptSet = map.keySet();
				for(String deptName : deptSet){
					int rows = 0;
					Map<String,List<ArrayList<TblOaDuty>>> deptMap = map.get(deptName);
					boolean siteInfo = false;
					//注意---------------------------修改部分
					Map<String, Integer> lenMap = new HashMap<String, Integer>();
					Set<String> keySet = deptMap.keySet();
					for(String scheduleId : keySet){
						lenMap.put(scheduleId, getMax(deptMap.get(scheduleId)));
					}
					
					Set<String> keySet2 = lenMap.keySet();
					for(String id : keySet2){
						rows += lenMap.get(id);
					}
					
					if(rows>=2){
						int row2 = sheet.getLastRowNum()+1;
						sheet.addMergedRegion(new CellRangeAddress(row2,row2+rows-1,0,0));
						sheet.addMergedRegion(new CellRangeAddress(row2,row2+rows-1,1,1));
					}
					
					for(String id:keySet){
						int thislen =lenMap.get(id);
						String scheduleName = "";
						String deptTelNo = "";
						String startTime = "";
						String endTime = "";
						List<ArrayList<TblOaDuty>> list = deptMap.get(id);
						for(int k=0;k<list.size();k++){
							if(list.get(k).size()>0){
							scheduleName = list.get(k).get(0).getScheduleName();
							deptName = list.get(k).get(0).getDeptName();
							deptTelNo = list.get(k).get(0).getDeptTelNo();
							startTime =list.get(k).get(0).getStartTime();
							endTime = list.get(k).get(0).getEndTime();
							break;
							}else {
								continue;
							}
						}
						
						if(thislen>=2){
							int row1 = sheet.getLastRowNum()+1;
							sheet.addMergedRegion(new CellRangeAddress(row1,row1+thislen-1,2,2));
						}
						for (int j = 0; j < thislen; j++) {
							//设置公司和部门值
							row = sheet.createRow(sheet.getLastRowNum() + 1);
							if(!siteInfo&&j==0){
								cell = row.createCell(0);
								cell.setCellStyle(style);
								cell.setCellValue(expSiteName);
								cell = row.createCell(1);
								cell.setCellStyle(style);
								cell.setCellValue(deptName+deptTelNo);
								siteInfo = true;
							}
							if(j==0){
								cell = row.createCell(2);
								cell.setCellStyle(style);
								cell.setCellValue(scheduleName+"("+startTime+"-"+endTime+")");
							}
							cell = row.createCell(3);
							cell.setCellStyle(style);
							cell.setCellValue((list.get(0).size() != 0) && (list.get(0).size() > j)
								? list.get(0).get(j).getUserName()+list.get(0).get(j).getUserTelNo().split(",")[0]: "");
							
							cell = row.createCell(4);
							cell.setCellStyle(style);
							cell.setCellValue((list.get(1).size() != 0) && (list.get(1).size() > j)
								? list.get(1).get(j).getUserName()+list.get(1).get(j).getUserTelNo().split(",")[0]: "");
							
							cell = row.createCell(5);
							cell.setCellStyle(style);
							cell.setCellValue((list.get(2).size() != 0) && (list.get(2).size() > j)
								? list.get(2).get(j).getUserName()+list.get(2).get(j).getUserTelNo().split(",")[0]: "");
							
							cell = row.createCell(6);
							cell.setCellStyle(style);
							cell.setCellValue((list.get(3).size() != 0) && (list.get(3).size() > j)
								? list.get(3).get(j).getUserName()+list.get(3).get(j).getUserTelNo().split(",")[0]: "");
							
							cell = row.createCell(7);
							cell.setCellStyle(style);
							cell.setCellValue((list.get(4).size() != 0) && (list.get(4).size() > j)
								? list.get(4).get(j).getUserName()+list.get(4).get(j).getUserTelNo().split(",")[0]: "");
							
							cell = row.createCell(8);
							cell.setCellStyle(style);
							cell.setCellValue((list.get(5).size() != 0) && (list.get(5).size() > j)
								? list.get(5).get(j).getUserName()+list.get(5).get(j).getUserTelNo().split(",")[0]: "");
							
							cell = row.createCell(9);
							cell.setCellStyle(style);
							cell.setCellValue((list.get(6).size() != 0) && (list.get(6).size() > j)
								? list.get(6).get(j).getUserName()+list.get(6).get(j).getUserTelNo().split(",")[0]: "");
						}
					}
				}
				//设置响应头
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String((sheetName + ".xls").getBytes(), "iso-8859-1"));
				OutputStream ouputStream = response.getOutputStream();
				wb.write(ouputStream);
				ouputStream.flush();
				ouputStream.close();
				wb.close();
		}else{
		//所有查询结束
		//部门查询
		TblOaDuty tblOaDuty = new TblOaDuty();
		tblOaDuty.setSiteId(siteId);
		tblOaDuty.setDeptId(deptId);
		tblOaDuty.setDutyDate(dutyDate);

		List<TblOaDuty> dutyList = dutyService.selectDutys(tblOaDuty);
		if (dutyList.size() < 0) {
			System.out.println("导出值班表内容为空，已取消下载！！！！！！！！！！");
			return;
		}
		
		// 生成表名
		tblOaDuty = dutyList.get(0);
		String expSiteName = tblOaDuty.getSiteName();
		String expDeptName = tblOaDuty.getDeptName();
		String sheetName = expSiteName + expDeptName + date + "值班表";

		// 生成日期列名
		SimpleDateFormat formater2 = new SimpleDateFormat("MM/dd");
		String[] strs = new String[7];
		Calendar cal = Calendar.getInstance();
		cal.setTime(dutyDate);
		for (int i = 0; i < 7; i++) {
			String weekDay = getWeekDay(cal.getTime());
			strs[i] = formater2.format(cal.getTime()) + weekDay;
			cal.add(Calendar.DATE, 1);
		}
		//所有列名
		String[] title = { "所属公司", "部门", "班次", strs[0], strs[1], strs[2], strs[3], strs[4], strs[5], strs[6] };
		//封装数据到班次列表
		Map<String, List<ArrayList<TblOaDuty>>> scheduleMap = handleDutyData(dutyList,dutyDate);
		//计算合并参数
		Map<String, Integer> lenMap = new HashMap<String, Integer>();
		Set<String> keySet = scheduleMap.keySet();
		for(String scheduleId : keySet){
			lenMap.put(scheduleId, getMax(scheduleMap.get(scheduleId)));
		}
		int rows = 0;
		boolean siteInfo = false;
		Set<String> keySet2 = lenMap.keySet();
		for(String id : keySet2){
			rows += lenMap.get(id);
		}
		// 1.创建一个workbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 2.在workbook中添加一个sheet，对应Excel中的一个sheet
		HSSFSheet sheet = wb.createSheet(sheetName);
		for(int i=0;i<10;i++){
			sheet.setColumnWidth(i,8*2*256);
		}
		
		//2.1设置合并单元格
		if(rows>=2){
			sheet.addMergedRegion(new CellRangeAddress(1,rows,0,0));
			sheet.addMergedRegion(new CellRangeAddress(1,rows,1,1));
		}
		// 3.在sheet中添加表头第0行，老版本poi对excel行数列数有限制short
		sheet.createFreezePane(0, 1, 0, 1);
		HSSFRow row = sheet.createRow((int) 0);
		// 4.创建单元格，设置值表头，设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		// 居中格式
		style.setWrapText(true);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中 
		HSSFCell cell = null;
		for (int i = 0; i < title.length; i++) {
			cell = row.createCell(i);
			cell.setCellValue(title[i]);
			cell.setCellStyle(style);
		}
		//5.解析数据到excel    sheet.getLastRowNum()
		//for(int k=0;k<size;k++){},排序时选用
		for(String scheduleId : keySet){
			int thislen =lenMap.get(scheduleId);
			if(thislen>=2){
				int row1 = sheet.getLastRowNum()+1;
				sheet.addMergedRegion(new CellRangeAddress(row1,row1+thislen-1,2,2));
			}
			String scheduleName = "";
			String deptTelNo = "";
			String startTime = "";
			String endTime = "";
			List<ArrayList<TblOaDuty>> list = scheduleMap.get(scheduleId);
			//获取班次信息
			for(int k=0;k<list.size();k++){
				if(list.get(k).size()>0){
				scheduleName = list.get(k).get(0).getScheduleName();
				deptTelNo = list.get(k).get(0).getDeptTelNo();
				startTime =list.get(k).get(0).getStartTime();
				endTime = list.get(k).get(0).getEndTime();
				break;
				}else {
					continue;
				}
			}
		for (int j = 0; j < thislen; j++) {
			//设置公司和部门值
			row = sheet.createRow(sheet.getLastRowNum() + 1);
			if(!siteInfo&&j==0){
				cell = row.createCell(0);
				cell.setCellStyle(style);
				cell.setCellValue(expSiteName);
				cell = row.createCell(1);
				cell.setCellStyle(style);
				cell.setCellValue(expDeptName+deptTelNo);
				siteInfo = true;
			}
			if(j==0){
				cell = row.createCell(2);
				cell.setCellStyle(style);
				cell.setCellValue(scheduleName+"("+startTime+"-"+endTime+")");
			}
			cell = row.createCell(3);
			cell.setCellStyle(style);
			cell.setCellValue((list.get(0).size() != 0) && (list.get(0).size() > j)
				? list.get(0).get(j).getUserName()+list.get(0).get(j).getUserTelNo().split(",")[0]: "");
			
			cell = row.createCell(4);
			cell.setCellStyle(style);
			cell.setCellValue((list.get(1).size() != 0) && (list.get(1).size() > j)
				? list.get(1).get(j).getUserName()+list.get(1).get(j).getUserTelNo().split(",")[0]: "");
			
			cell = row.createCell(5);
			cell.setCellStyle(style);
			cell.setCellValue((list.get(2).size() != 0) && (list.get(2).size() > j)
				? list.get(2).get(j).getUserName()+list.get(2).get(j).getUserTelNo().split(",")[0]: "");
			
			cell = row.createCell(6);
			cell.setCellStyle(style);
			cell.setCellValue((list.get(3).size() != 0) && (list.get(3).size() > j)
				? list.get(3).get(j).getUserName()+list.get(3).get(j).getUserTelNo().split(",")[0]: "");
			
			cell = row.createCell(7);
			cell.setCellStyle(style);
			cell.setCellValue((list.get(4).size() != 0) && (list.get(4).size() > j)
				? list.get(4).get(j).getUserName()+list.get(4).get(j).getUserTelNo().split(",")[0]: "");
			
			cell = row.createCell(8);
			cell.setCellStyle(style);
			cell.setCellValue((list.get(5).size() != 0) && (list.get(5).size() > j)
				? list.get(5).get(j).getUserName()+list.get(5).get(j).getUserTelNo().split(",")[0]: "");
			
			cell = row.createCell(9);
			cell.setCellStyle(style);
			cell.setCellValue((list.get(6).size() != 0) && (list.get(6).size() > j)
				? list.get(6).get(j).getUserName()+list.get(6).get(j).getUserTelNo().split(",")[0]: "");
			}
		}
		//设置响应头
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((sheetName + ".xls").getBytes(), "iso-8859-1"));
		/*String user_Agent= request.getHeader("User-Agent");
		if( user_Agent.contains("Firefox") ){
			Base64Encoder base64Encoder = new Base64Encoder();
			sheetName = "=?utf-8?B?"	+ base64Encoder.encode(sheetName.getBytes("utf-8")) + "?=";
		}else{
			sheetName = URLEncoder.encode(sheetName, "utf-8");
		}
		//告诉浏览器，当前下载的文件名的名称
		response.setHeader("Content-Disposition", "attachment;filename=" + sheetName);*/
		
		OutputStream ouputStream = response.getOutputStream();
		wb.write(ouputStream);
		ouputStream.flush();
		ouputStream.close();
		wb.close();
		}
	}

	/**
	 * 获取用户默认选择的站点
	 * 
	 * @return
	 */
	private String getDefaultSiteId() {
		UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		ArrayList<String> remainList = new ArrayList<String>();
		if (!"769000".equalsIgnoreCase(user.getSiteId())) {
			remainList.add(user.getSiteId());
		}
		Object auths[] = SecurityContextHolder.getContext().getAuthentication().getAuthorities().toArray();
		for (Object o : auths) {
			String auth = o + "";
			if (auth.contains("MANAGE_CHECK_")) {
				String siteId = auth.substring(13, 19);
				if (!remainList.contains(siteId)) {
					remainList.add(siteId);
				}
			}
		}
		if (!CollectionUtils.isEmpty(remainList)) {
			return remainList.get(0);
		}
		return null;
	}
	//站点ID是否合法
	private boolean isLegalSiteId(String siteId) {
		if (StringUtils.isBlank(siteId))
			return false;
		UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		ArrayList<String> remainList = new ArrayList<String>();
		if (!"769000".equalsIgnoreCase(user.getSiteId())) {
			remainList.add(user.getSiteId());
		}
		Object auths[] = SecurityContextHolder.getContext().getAuthentication().getAuthorities().toArray();
		for (Object o : auths) {
			String auth = o + "";
			if (auth.contains("MANAGE_CHECK_")) {
				String s = auth.substring(13, 19);
				if (!remainList.contains(s)) {
					remainList.add(s);
				}
			}
		}
		if (!CollectionUtils.isEmpty(remainList)) {
			if (remainList.contains(siteId)) {
				return true;
			}
		}
		return false;
	}

	// 封装值班信息到三个班次列表中
	public Map<String,List<ArrayList<TblOaDuty>>> handleDutyData(List<TblOaDuty> list,Date mondayDate) {
		Map<String,List<ArrayList<TblOaDuty>>> scheduleMap = new HashMap<String,List<ArrayList<TblOaDuty>>>();
		if (list != null && list.size() > 0) {
			for (TblOaDuty duty : list) {
				int days = getDay(mondayDate, duty.getDutyDate());
				if(!scheduleMap.containsKey(duty.getScheduleId())){
					List<ArrayList<TblOaDuty>> intiList = new ArrayList<ArrayList<TblOaDuty>>();
					for(int i=0;i<7;i++){
						intiList.add(new ArrayList<TblOaDuty>());
					}
					scheduleMap.put(duty.getScheduleId(), intiList);
				}
				List<ArrayList<TblOaDuty>> dutyList = scheduleMap.get(duty.getScheduleId());
				switch (days) {
				case 0:
					dutyList.get(0).add(duty);
					break;
				case 1:
					dutyList.get(1).add(duty);
					break;
				case 2:
					dutyList.get(2).add(duty);
					break;
				case 3:
					dutyList.get(3).add(duty);
					break;
				case 4:
					dutyList.get(4).add(duty);
					break;
				case 5:
					dutyList.get(5).add(duty);
					break;
				case 6:
					dutyList.get(6).add(duty);
					break;
				}
			}
		}
		return scheduleMap;
	}
	
	//获取部门班次信息并加载到datagrid
	@RequestMapping("/datagridSchedules")
	@ResponseBody
	public List<Map<String, Object>> datagridSchedules(HttpServletRequest request, HttpServletResponse response, DutyForm form) {
		String siteId = form.getSiteId();
		String deptId = form.getDeptId();
		List<Map<String, Object>> list = dutyService.datagridSchedules(siteId,deptId);
		return  list;
	}
	
	//获取个人电话信息并加载到datagrid
	@RequestMapping("/datagridTelNo")
	@ResponseBody
	public List<Map<String,String>> datagridTelNo(HttpServletRequest request, HttpServletResponse response, DutyForm form) {
		String userId = form.getUserId();
		String telNo = dutyService.datagridTelNo(userId);
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		HashMap<String, String> telNoMap = new HashMap<String,String>();
		telNoMap.put("userId", userId);
		telNoMap.put("telNo", telNo);
		list.add(telNoMap);
		return  list;
	}
	
	//获取部门电话信息并加载到datagrid
	@RequestMapping("/datagridDeptTelNo")
	@ResponseBody
	public Map<String,String> datagridDeptTelNo(HttpServletRequest request, HttpServletResponse response, DutyForm form) {
		String deptId = form.getDeptId();
		String siteId = form.getSiteId();
		String telNo = dutyService.datagridDeptTelNo(siteId,deptId);
		HashMap<String, String> telNoMap = new HashMap<String,String>();
		telNoMap.put("deptId", deptId);
		telNoMap.put("siteId", siteId);
		telNoMap.put("telNo", telNo);
		return  telNoMap;
	}
	
	@RequestMapping("/datagridSites")
	@ResponseBody
	public List<Map<String, Object>> datagridSites() {
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		List<TsSiteinfo> siteList = companyService.selectDirectSites();
		for (TsSiteinfo site: siteList) {
			Map<String, Object> siteMap = new HashMap<String, Object>();
			siteMap.put("siteId", site.getSiteid());
			siteMap.put("siteName", site.getSitename());
			list.add(siteMap);
		}
		return list;
	}
	
	@RequestMapping("/datagridDepts")
	@ResponseBody
	public List<Map<String, Object>> datagridDepts(HttpServletRequest request, HttpServletResponse response, DutyForm form) {
		String siteId = form.getSiteId();
		return dutyService.datagridDepts(siteId);
	}
	
	@RequestMapping("/datagridUsers")
	@ResponseBody
	public List<Map<String, Object>> datagridUser(HttpServletRequest request, HttpServletResponse response, DutyForm form) {
		String siteId = form.getSiteId();
		String deptId = form.getDeptId();
		return dutyService.datagridUsers(siteId,deptId);
	}
	
	//获取班次开始结束时间信息
	@RequestMapping("/scheduleTime")
	@ResponseBody
	public Map<String,String> scheduleTime(HttpServletRequest request, HttpServletResponse response, DutyForm form) {
		String scheduleId = form.getScheduleId();
		TblOaDutySchedule schedule = dutyService.selectScheduleTime(scheduleId);
		HashMap<String, String> telNoMap = new HashMap<String,String>();
		telNoMap.put("startTime", schedule.getStartTime()!=null?schedule.getStartTime():"");
		telNoMap.put("endTime", schedule.getEndTime()!=null?schedule.getEndTime():"");
		return  telNoMap;
	}
	
	//获取周一日期
	public Date getMondayDate(String date) {
		Date parseDate = new Date();
		if(date==null||date.equals("")){
			return parseDate;
		}
		try {
			parseDate = DateUtils.parseDate(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(parseDate);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		return cal.getTime();
	}

	// 获取某一天是星期几
	public String getWeekDay(Date d) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(d);
		int index = cal.get(Calendar.DAY_OF_WEEK);
		String[] weeks = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		return weeks[index - 1];
	}

	// 获取没个列表中最大的size
	public int getMax(List<ArrayList<TblOaDuty>> list) {
		int len = list.get(0).size();
		for (int i = 1; i < list.size(); i++) {
			if (list.get(i).size() > len) {
				len = list.get(i).size();
			}
		}
		return len;
	}

	// 获取两个日期之间天数差
	public int getDay(Date fDate, Date oDate) {

		Calendar aCalendar = Calendar.getInstance();

		aCalendar.setTime(fDate);

		int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);

		aCalendar.setTime(oDate);

		int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);

		return day2 - day1;

	}
	
}
